package com.zhanglu.fun.services.chatroom.config;

import com.zhanglu.fun.services.chatroom.security.AuthLogoutHandler;
import com.zhanglu.fun.services.chatroom.security.PreAuthFilter;
import com.zhanglu.fun.tookit.jwt.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @description
 * @Auther zhanglu
 * @Date 2017/10/19 下午3:17
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true) // 开启@Secured，但是里面值必须是ROLE_开头
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private PreAuthFilter      preAuthFilter;
    @Autowired
    private AuthLogoutHandler  logoutHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
            .disable()// 由于使用的是JWT，我们这里不需要csrf
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()// 基于token，所以不需要session
            .authorizeRequests()
            .antMatchers("/","/robot.html","/auth/**").permitAll()// 对于获取token的rest api要允许匿名访问
            .antMatchers("/test/**").permitAll()// 所有test测试路径全部可以访问。正是环境删掉test
            .anyRequest().authenticated()
            .and()// 除上面外的所有请求全部需要鉴权认证
            // .addFilterAfter(remoteAuthFilter, PreAuthFilter.class) //这里一直跳不到cookie，登陆单独写了。回头在研究登陆过滤器
            .addFilterBefore(preAuthFilter, UsernamePasswordAuthenticationFilter.class)
            .logout()
            .addLogoutHandler(logoutHandler)
            .deleteCookies(JwtUtil.COOKIE_AUTH);
            // .and().formLogin();
    }

    // 忽略静态资源的拦截
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/static/**");
    }
}
